package com.yoso.log.infrastructure.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.yoso.log.application.service.IOrderLogService;
import com.yoso.log.application.service.IStockLogService;
import com.yoso.log.interfaces.vo.OrderLogVo;
import com.yoso.log.interfaces.vo.StockLogVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @author shizejin
 * @date 2022/1/30
 * @description: 接受订单日志消息
 */
@Component
@Slf4j
public class LogMsgConsumer {
    @Autowired
    private IOrderLogService orderLogService;
    @Autowired
    private IStockLogService stockLogService;

    /**
     * 更新订单日志
     */
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(value = "${rabbitmq.queue.log.shop.order}", autoDelete = "true"),
                    exchange = @Exchange(value = "${rabbitmq.exchange.log.shop.order}", type = ExchangeTypes.FANOUT)
            )
    })
    public void flushOrderLog(Message message) {
        String result;
        String jsonString = new String(message.getBody(), StandardCharsets.UTF_8);
        OrderLogVo orderLogVo = JSON.parseObject(jsonString, OrderLogVo.class);
        orderLogVo.setId(null);
        log.info("收到订单通知:{}", JSON.toJSONString(orderLogVo));
        int row = orderLogService.insert(orderLogVo);
        result = row == 1 ? "订单日志添加成功" : "订单日志添加失败";
        log.info(result);
    }

    /**
     * 更新库存日志
     */
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(value = "${rabbitmq.queue.log.shop.stock}", autoDelete = "true"),
                    exchange = @Exchange(value = "${rabbitmq.exchange.log.shop.stock}", type = ExchangeTypes.FANOUT)
            )
    })
    public void flushStockLog(Message message) {
        String result;
        String jsonString = new String(message.getBody(), StandardCharsets.UTF_8);
        StockLogVo stockLogVo = JSON.parseObject(jsonString, StockLogVo.class);
        log.info("收到库存更新通知:{}", JSON.toJSONString(stockLogVo));
        stockLogVo.setId(null);
        int row = stockLogService.insert(stockLogVo);
        result = row == 1 ? "库存日志添加成功" : "库存日志添加失败";
        log.info(result);
    }
}
